package cn.lj.logistics.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.tags.EditorAwareTag;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.lj.logistics.pojo.MsgObject;
import cn.lj.logistics.pojo.Role;
import cn.lj.logistics.pojo.RoleExample;
import cn.lj.logistics.pojo.User;
import cn.lj.logistics.pojo.UserExample;
import cn.lj.logistics.pojo.UserExample.Criteria;
import cn.lj.logistics.service.RoleService;
import cn.lj.logistics.service.UserService;


@Controller
@RequestMapping("/admin")
public class AdminController {
     
	@Autowired
	private UserService userService;
	
	@Autowired
	private RoleService roleService;
	
	//编辑页面，新增和修改公用的页面
	@RequestMapping("/edit")
	public String edit(Model m,Long userId) {
		
		//修改操作
		if (userId!=null) {
			// 查询出当前用户的数据，共享给编辑页面，以供修改回显数据
			User user = userService.selectByPrimaryKey(userId);
			m.addAttribute("user",user);
		}
		
		// 查询出所有的角色，以供新增修改管理员分配角色信息
		RoleExample example=new RoleExample();
		List<Role> roles = roleService.selectByExample(example);
		m.addAttribute("roles", roles);
		
		return "adminEdit";
		
	}
	
	// 检查用户名是否存在
	@RequestMapping("/checkUsername")
	@ResponseBody
	public boolean checkUsername(String username) {
		
		UserExample example=new UserExample();
	   Criteria criteria = example.createCriteria();
	   criteria.andUsernameEqualTo(username);
	   
		List<User> users = userService.selectByExample(example);
		
		return users.size() == 0 ? true :false;
		
	}
	
	//新增功能
		@RequestMapping("/insert")
		@RequiresPermissions("admin:insert")
		@ResponseBody
		public MsgObject insert(User user) {
			
			
			//设置入职日期
			user.setCreateDate(new Date());
			
			/*
			 * 使用MD5+盐*散列三次 （后面的安全管理使用Shiro安全框架）
			 */
			//设置盐
			String salt = UUID.randomUUID().toString().substring(0, 5);
			user.setSalt(salt);
			//设置加密后的密码
			Md5Hash md5Hash = new Md5Hash(user.getPassword(), salt, 3);
			user.setPassword(md5Hash.toString());
		int row = userService.insert(user);
			MsgObject mo = MsgObject.createMO(0, "新增数据失败，请联系管理员！！！");
			if (row==1) {
				mo=MsgObject.createMO(1, "新增数据成功");
			}
			return mo;
			
		}
		
		//修改功能
				@RequestMapping("/update")
				@RequiresPermissions("admin:update")
				@ResponseBody
				public MsgObject update(User user) {
				
					
					/*
					 * 使用MD5+盐*散列三次 （后面的安全管理使用Shiro安全框架）
					 */
					//设置盐
					String salt = UUID.randomUUID().toString().substring(0, 5);
					user.setSalt(salt);
					//设置加密后的密码
					Md5Hash md5Hash = new Md5Hash(user.getPassword(), salt, 3);
					user.setPassword(md5Hash.toString());
				int row = userService.updateByPrimaryKeySelective(user);
					MsgObject mo = MsgObject.createMO(0, "修改数据失败，请联系管理员！！！");
					if (row==1) {
						mo=MsgObject.createMO(1, "修改数据成功");
					}
					return mo;
					
				}
		
	
	//删除功能
	@RequestMapping("/delete")
	@RequiresPermissions("admin:delete")
	@ResponseBody
	public MsgObject delete(Long userId) {
		int row = userService.deleteByPrimaryKey(userId);
		MsgObject mo = MsgObject.createMO(0, "删除数据失败，请联系管理员！！！");
		if (row==1) {
			mo=MsgObject.createMO(1, "删除数据成功");
		}
		return mo;
		
	}
	
	//批量删除功能
	@RequestMapping("/batchDelete")
	@RequiresPermissions("admin:delete")
	@ResponseBody
	public MsgObject batchDelete(String ids) {
		
		// 切割字符串：1，2，3...
		String[] userIds = ids.split(",");
		
		//组装数组
		List<Long> userIdsList=new ArrayList<Long>();
		for (String userId : userIds) {
			userIdsList.add(Long.valueOf(userId));
		}
		
		UserExample example=new UserExample();
		Criteria criteria = example.createCriteria();
		criteria.andUserIdIn(userIdsList);
		
		int row = userService.deleteByExample(example);
		
		MsgObject mo = MsgObject.createMO(0, "删除数据失败，请联系管理员！！！");
		if (row>=1) {
			mo=MsgObject.createMO(1, "删除数据成功");
		}
		return mo;
		
	}
	
	@RequestMapping("/adminPage")
	@RequiresPermissions("admin:adminPage")
	public String adminPage() {
		
		return "adminPage";
		
	}
	//认证失败跳转页面
	@RequestMapping("/login")
	public String login(HttpServletRequest request ,Model m) {
		// 获取认证失败的错误信息'
				String shiroLoginFailure = (String) request.getAttribute("shiroLoginFailure");
				System.out.println("shiroLoginFailure :" + shiroLoginFailure);
				// org.apache.shiro.authc.UnknownAccountException
				// org.apache.shiro.authc.IncorrectCredentialsException
				if (UnknownAccountException.class.getName().equals(shiroLoginFailure)) {
				   m.addAttribute("errorMsg","亲，账号不存在");	
				}else if (IncorrectCredentialsException.class.getName().equals(shiroLoginFailure)) {
					m.addAttribute("errorMsg", "亲，密码错误");
				}

				return "forward:/login.jsp";
		
	}
	
	
	
	@RequestMapping("/list")
	@RequiresPermissions("admin:list")
	@ResponseBody
	public PageInfo<User> list(@RequestParam(defaultValue = "1")Integer pageNum,
			               @RequestParam(defaultValue = "10")Integer pageSize ,String keyword){
		System.out.println("keyword:"+ keyword);
		//开始分页
		PageHelper.startPage(pageNum, pageSize);
		UserExample example=new UserExample();
		
		if (StringUtils.isNotBlank(keyword)) {
			// 创建限制对象
			Criteria criteria1 = example.createCriteria();
		criteria1.andRealnameLike("%"+keyword+"%"); 
		
		Criteria criteria2 = example.createCriteria();
		criteria2.andUsernameLike("%"+keyword+"%");
		example.or(criteria2);
		
		
		Criteria criteria3 = example.createCriteria();
	     criteria3.andRolenameLike("%"+keyword+"%");
		example.or(criteria3);
		}
		List<User> list = userService.selectByExample(example);
		
		return  new PageInfo<User>(list);
		
	}
}
